using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.VersionControl.Client;

namespace Microsoft.Vsts.Ranger.Migration.TfsToTfs.Client
{
    public class TfsHelper
    {
        private TeamFoundationServer _server;

        public bool TfsConnect(string serverName, bool useStoredCredentials)
        {
            try
            {
                TeamFoundationServer server;

                if (useStoredCredentials)
                {
                    server = new TeamFoundationServer(serverName, new StoredCredentialsProvider());
                }
                else
                {
                    server = new TeamFoundationServer(serverName);
                }

                server.Authenticate();

                _server = server;

                return true;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Error Connecting to server.  Message Follows: " + ex.Message);

                return false;
            }
        }

        public string GetServerUri()
        {
            return _server.Uri.ToString();
        }

        public List<string> GetTeamProjects()
        {
            ICommonStructureService css = (ICommonStructureService)_server.GetService(typeof(ICommonStructureService));

            List<string> projectNames = new List<string>();

            ProjectInfo[] projects = css.ListAllProjects();

            foreach (ProjectInfo pi in projects)
                projectNames.Add(pi.Name);


            return projectNames;
        }

        //public List<string> GetWorkspaces()
        //{
        //    VersionControlServer vcs = (VersionControlServer)_server.GetService(typeof(VersionControlServer));

        //    vcs.GetTeamProject("FDF").VersionControlServer.TryGetWorkspace(

        //    WorkspaceInfo wi;

            

        //}


        public ItemSet GetVCTree(string teamProject)
        {            
            VersionControlServer vcs = (VersionControlServer)_server.GetService(typeof(VersionControlServer));
            
            ItemSet items =  vcs.GetItems("$/" + teamProject,RecursionType.None);

            return items;
        }
    }
}